package com.gin.kotlin.no_gay_alliance.fragment.post

import android.os.Bundle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.argument.AttachmentArgument
import com.gin.kotlin.no_gay_alliance.argument.UploadArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.base.FragmentStateContainer
import com.gin.kotlin.no_gay_alliance.databinding.FragmentPostAttachmentBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

/**
 * 上传附件和已有附件标签
 * @property uploadArgument 上传参数
 * @property attachmentArgument 已有附件参数
 * @property tabLayoutMediator TabLayoutMediator
 * @property tabs List<FragmentStateContainer>
 */
class PostAttachmentFragment : AbstractBindingFragment<FragmentPostAttachmentBinding>(), TabLayoutMediator.TabConfigurationStrategy {
    private lateinit var uploadArgument: UploadArgument
    private lateinit var attachmentArgument: AttachmentArgument
    private lateinit var tabLayoutMediator: TabLayoutMediator
    private lateinit var tabs: List<FragmentStateContainer>

    /**
     * onCreateView的后续操作 ，如通过  [FragmentActivity.addMenuProvider] 添加菜单
     */
    override fun onCreateView() {
        val b = this.b ?: return

        // 表情分组标签
        this.tabs = listOf(
            FragmentStateContainer(title = "上传附件") { PostAttachmentUploadFragment.newInstance(uploadArgument) },
            FragmentStateContainer(title = "已有附件(${attachmentArgument.attachments?.size ?: 0})") { PostAttachmentManagerFragment.newInstance(attachmentArgument) },
        )

        // 为ViewPager2设置适配器
        b.viewPager2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = tabs.size
            override fun createFragment(position: Int) = FragmentStateContainer.newInstance(tabs, position)
        }
        this.tabLayoutMediator = attachTabLayout(b.tabLayout, b.viewPager2, this)

    }

    override fun handleArguments(bundle: Bundle) {
        super.handleArguments(bundle)
        this.uploadArgument = parseBundle(bundle, UploadArgument::class.java.simpleName, UploadArgument::class.java)
        this.attachmentArgument = parseBundle(bundle, AttachmentArgument::class.java.simpleName, AttachmentArgument::class.java)
    }

    override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
        this.tabs[position].title?.also { tab.text = it }
    }

    companion object {
        fun newInstance(uploadArgument: UploadArgument, attachmentArgument: AttachmentArgument) =
            PostAttachmentFragment().also {
                it.arguments = Bundle().also { b ->
                    b.putParcelable(UploadArgument::class.java.simpleName, uploadArgument)
                    b.putParcelable(AttachmentArgument::class.java.simpleName, attachmentArgument)
                }
            }
    }
}